package com.skyline.wo.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.skyline.base.exception.NoResourceException;
import com.skyline.base.type.ResourceType;
import com.skyline.common.bean.Page;
import com.skyline.feed.service.PersonalFeedService;
import com.skyline.wo.dao.ArticleDao;
import com.skyline.wo.dao.CategoryDao;
import com.skyline.wo.dao.ResourceDao;
import com.skyline.wo.model.Article;
import com.skyline.wo.service.ArticleService;

@Service("articleService")
public class ArticleServicleImpl implements ArticleService {

	@Autowired
	private ArticleDao articleDao;

	@Autowired
	private CategoryDao categoryDao;

	@Autowired
	private ResourceDao resourceDao;

	@Autowired
	private PersonalFeedService personalFeedService;

	@Override
	public void modifyArticle(Long id, Integer authority, Long ownerId, String title, String content, String digest, Long categoryId,
			String categoryName) {
		articleDao.updateArticle(id, authority, ownerId, title, content, digest, categoryId, categoryName);
	}

	@Override
	public void addArticle(Article a) {
		long id=articleDao.insertArticle(a.getAuthority(), a.getOwnerId(), a.getOwnerPortrait(), a.getOwnerNickname(), a.getTitle(), a.getContent(),
				a.getDigest(), a.getCategoryId(), a.getCategoryName());
		categoryDao.updateArticleNumAdd(a.getCategoryId(), a.getOwnerId(), 1);
		a.setId(id);
		personalFeedService.addArticleFeed(a);
	}

	public List<Article> getArticleByOwnerId(Page page, Long ownerId, Integer authority) {
		return articleDao.queryArticleByOwnerId(page, ownerId, authority);
	}

	public List<Article> getArticleByCategoryId(Page page, Long categoryId,Long ownerId, Integer authority) {
		return articleDao.queryArticleByCategoryId(page, categoryId, ownerId,authority);
	}

	public Article getPriorArticle(Long categoryId, Long id, Integer authority) {
		return articleDao.queryPriorArticleById(categoryId, id, authority);
	}

	public Article getNextArticle(Long categoryId, Long id, Integer authority) {
		return articleDao.queryNextArticleById(categoryId, id, authority);
	}

	public Article getArticleById(Long id) {
		Article article = articleDao.queryArticleById(id);
		if (article == null) {
			throw new NoResourceException();
		} else {

			return article;
		}
	}

	public void addVisitNum(Long id) {
		articleDao.updateArticleVisitNum(id);
	}

	public void deleteArticle(Long id, Long actionerId) {
		Article article = articleDao.queryArticleById(id);
		if (article != null) {
			articleDao.deleteArticle(id, actionerId);
			categoryDao.updateArticleNumMinus(article.getCategoryId(), actionerId, 1);
		}
	}

	public void up(Long id) {
		resourceDao.updateUpOfOne(ResourceType.ARTICLE, id);
	}

	public void down(Long id) {
		resourceDao.updateDownOfOne(ResourceType.ARTICLE, id);
	}

}
